<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Cmis File Picker</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="bower_components/fontawesome/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="dist/style.default.min.css" />
    <style type="text/css">
        html,body,#testThis{
            height: 100%;
        }
        #testThis{
            position: absolute;
            top: 60px;
            bottom: 0;
            left: 0;
            right: 0;
        }
        .test-qq{
            position: absolute;
            height: 60px;
            top: 0;
            width: 100%;
        }
        .navbar-fixed-top{
            position: absolute;
        }
    </style>
</head>
<body >
<div class="test-qq">
    <a class="test">admin@qqq.com</a>
    <a class="test">38@qq.com</a>
    <a class="test">15@gmail.com</a>
    <a class="test">14@gmail.com</a>
    <a class="test">22@gmail.com</a>
    <a class="test">33@gmail.com</a>
    <a class="test">admin@gmail.com</a>
    <a id="changePath">切换路径</a>
</div>
<div id="testThis">
</div>

<script type="text/javascript" src="src/language/da-DK.js"></script>
<script type="text/javascript" src="src/language/de-DE.js"></script>
<script type="text/javascript" src="src/language/en-US.js"></script>
<script type="text/javascript" src="src/language/es-419.js"></script>
<script type="text/javascript" src="src/language/fr-FR.js"></script>
<script type="text/javascript" src="src/language/it-IT.js"></script>
<script type="text/javascript" src="src/language/ja-JP.js"></script>
<script type="text/javascript" src="src/language/ko-KR.js"></script>
<script type="text/javascript" src="src/language/nl-NL.js"></script>
<script type="text/javascript" src="src/language/pl-PL.js"></script>
<script type="text/javascript" src="src/language/pt-PT.js"></script>
<script type="text/javascript" src="src/language/pt-BR.js"></script>
<script type="text/javascript" src="src/language/ru-RU.js"></script>
<script type="text/javascript" src="src/language/fi-FI.js"></script>
<script type="text/javascript" src="src/language/nb-NO.js"></script>
<script type="text/javascript" src="src/language/sv-SE.js"></script>
<script type="text/javascript" src="src/language/zh-CN.js"></script>
<script type="text/javascript" src="src/language/zh-HK.js"></script>
<script type="text/javascript" src="src/language/zh-TW.js"></script>

<script type="text/javascript" src="bower_components/FileSaver/FileSaver.min.js"></script>
<script type="text/javascript" src="bower_components/base64/base64.min.js"></script>
<script type="text/javascript" src="bower_components/superagent/superagent.js"></script>
<script type="text/javascript" src="bower_components/smx-cmis/lib/cmis.js"></script>
<script type="text/javascript" src="bower_components/angular/angular.js"></script>
<script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<script type="text/javascript" src="bower_components/angular-local-storage/dist/angular-local-storage.js"></script>
<script type="text/javascript" src="bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script type="text/javascript" src="bower_components/angular-translate/angular-translate.js"></script>
<script type="text/javascript" src="bower_components/angular-toastr/dist/angular-toastr.tpls.js"></script>
<script type="text/javascript" src="lib/ng-context-menu.js"></script>
<script type="text/javascript" src="lib/hover-menu.js"></script>
<script type="text/javascript" src="bower_components/angular-file-model/angular-file-model.js"></script>
<script type="text/javascript" src="bower_components/clipboard/dist/clipboard.js"></script>
<script type="text/javascript" src="bower_components/ngclipboard/dist/ngclipboard.js"></script>
<script type="text/javascript" src="bower_components/ngInfiniteScroll/build/ng-infinite-scroll.js"></script>
<script type="text/javascript" src="bower_components/angular-animate/angular-animate.js"></script>
<script type="text/javascript" src="bower_components/jquery-qrcode/jquery.qrcode.min.js"></script>
<script type="text/javascript" src="bower_components/clipboard/dist/clipboard.js"></script>

<!-- develop -->
<script type="text/javascript" src="src/cmis-directive.js"></script>
<script type="text/javascript" src="src/service.js"></script>
<script type="text/javascript" src="src/controllers.js"></script>
<script type="text/javascript" src="src/models.js"></script>
<script type="text/javascript" src="src/main-controller.js"></script>
<script type="text/javascript" src="src/modal-controller.js"></script>
<script type="text/javascript" src="src/filter.js"></script>
<script type="text/javascript" src="src/directives/file-dropzone.js"></script>
<script type="text/javascript" src="src/directives/drag-and-drop.js"></script>
<script type="text/javascript" src="src/directives/selection-area.js"></script>
<script type="text/javascript" src="src/directives/breadcrumb.js"></script>
<script type="text/javascript" src="src/directives/common.js"></script>



<script type="text/javascript">

    var baseUrl = 'https://cloud-docker.connectedpdf.com';
    var baseCWebPDFApi = 'hello world';

    var queryString = document.location.search.substring(1);
    var urlInfoParams = parseQueryString(queryString);

    /**
     * Helper function to parse query string (e.g. ?param1=value&parm2=...).
     */
    function showSignInModal(){
        window.top.PhantomOnline.showSignInModal();
    }
    function showSignUpModal(){
        window.top.PhantomOnline.showSignUpModal();
    }
    function translateStr(str,tarLanguage){
        if (!String.prototype.trim) {
            String.prototype.trim = function () {
                return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
            };
        }
        str = str.trim();
        try {
            if(window.CmisLanguage[tarLanguage || getDefaultLang()] && window.CmisLanguage[tarLanguage || getDefaultLang()][str]){
                return window.CmisLanguage[tarLanguage || getDefaultLang()][str];
            }else if(window.CmisLanguage['en-US'][str]){
                return window.CmisLanguage['en-US'][str];
            }else{
                return str;
            }

        } catch (ex) {}
    }
    function translateCommonText(){
        $('.translate').each(function( index ) {
            var $this = $(this);
            var placeholder;
            if(this.placeholder){
                this.placeholder = translateStr(this.placeholder,getDefaultLang());
            }
            if($this.attr('title')){
                $this.attr('title',translateStr($this.attr('title'),getDefaultLang()))
            }
            if($this.text()){

                $this.html(translateStr($this.text(),getDefaultLang()))
            }
        });
    }
    function getDefaultLang(){
        if(urlInfoParams['lang']){
            if(urlInfoParams['lang'].indexOf('-')!==-1){
                return urlInfoParams['lang'].split('-')[1];
            }else{
                return 'US';
            }
        }else {
            return 'US';
        }
    }
    function parseQueryString(query) {
        var parts = query.split('&');
        var params = {};
        for (var i = 0, ii = parts.length; i < ii; ++i) {
            var param = parts[i].split('=');
            var key = param[0].toLowerCase();
            var value = param.length > 1 ? param[1] : null;
            params[decodeURIComponent(key)] = decodeURIComponent(value);
        }
        return params;
    }
    $(document).ready(function(){
        translateCommonText()
        if(urlInfoParams['path']){
            // file_shared_with_me
            $('.shared-with-me').removeClass('hide');
        }else{
            // reading
            $('.my-drive').removeClass('hide');

        }
    })
    ;(function(){
        var calculatePath = function(userEmail){
            var result,path;
            var lowerEmail = userEmail.toLowerCase();
            var cleanId = (lowerEmail+'aaaa').replace(/[^a-zA-Z]/g,'');
            result = cleanId.substring(0,2)+'/'+cleanId.substring(2,4)+'/'+encodeURIComponent(lowerEmail);
            // result = cleanId.substring(0,2)+'/'+cleanId.substring(2,4)+'/'
            var paramsPath = urlInfoParams['path'];
            // if(paramsPath){
            //     path = '/User_Homes/'+result+'/'+paramsPath;
            // }else{
            //     path = '/User_Homes/'+result+'/Reading';
            // }
          console.log('=====result');
            console.log(result);
            // path = '/User_Homes/'+result+'/Reading/ConnectedPDF';
            if(paramsPath){
                path = '/User_Homes/'+result+'/Reading/ConnectedPDF';
            }else{
                path = '/User_Homes/'+result+'/Reading';
            }
            return path;
        };

        var urlParaToObj = function(urlPara, needEncode) {
            var arr, i, k, len1, obj;
            obj = {};
            if (urlPara.indexOf('&') !== -1) {
                arr = urlPara.split('&');
                for (k = 0, len1 = arr.length; k < len1; k++) {
                    i = arr[k];
                    if (needEncode) {
                        obj[i.split('=')[0]] = encodeURIComponent(i.split('=')[1]);
                    } else {
                        obj[i.split('=')[0]] = i.split('=')[1];
                    }
                }
            } else {
                if (needEncode) {
                    obj[urlPara.split('=')[0]] = encodeURIComponent(i.split('=')[1]);
                } else {
                    obj[urlPara.split('=')[0]] = urlPara.split('=')[1];
                }
            }
            return obj;
        };
        var getArgsFromUrl = function(url) {
            var index, result, urlParas;
            if (!url) {
                url = location.href;
            }
            index = url.indexOf('?');
            if (index === -1) {

            } else {
                urlParas = url.slice(index + 1);
                result = urlParaToObj(urlParas);
//            console.log(result);
                return result;
            }
        };
        var isTokenExpires = function(token,successfulCallback,errorCallback,baseUrl,apiPath,type){
            //https://cloud-docker.connectedpdf.com/api/auth/get_user_info?access-token=58aa5d7de4b0b7dd7200ad18%2Cww002%40mailinator.com
            if(!baseUrl){
                baseUrl=window.location.protocol+"//"+window.location.host;   //origin  https://cloud-docker.connectedpdf.com
            }
            if(!apiPath){
                apiPath='/api/auth/get_user_info';
            }
            if(!type){
                type='POST';
            }
            $.ajax({
                type:type,
                url:baseUrl+apiPath+'?access-token='+token,
                success:function(data){
                    if(typeof successfulCallback=='function' && data){
                        if (data.ret===0){
                            successfulCallback(data)
                        }else{
                            errorCallback(data)
                        }
                    }
                },
                error:function(data){
                    if(typeof errorCallback=='function'){
                        errorCallback(data)
                    }
                }
            })
        };
        var $cleanCopy = $('#testThis').clone();
        function generateCmisTag(url,className,token,path,language,baseUrl,device,cmistagstr,phantomSubscriptionStatus){
            console.log(cmistagstr);
            console.log('urlInfoParams',urlInfoParams);
            var cmisTag = '<cmis url="'+ url +'" token="'+ token +'" ' +
                'path="'+ path +'" ' +
                'lang="'+ language +'"'+
                'phantom-subscription-status="'+ phantomSubscriptionStatus +'"'+
                ' repository ="fxcld"' +
                'cpdf-base-url="https://cws-docker.connectedpdf.com/"'+
                'cpdf-doc-base-url="https://cpdfdoc-docker.connectedpdf.com/"'+
                'cweb-tools-api="http://cwebtools-docker.connectedpdf.com/convert.jsp"'+
                'doc-owner="false"'+
                ' base-url="'+ baseUrl +'"'+
                ' device="'+ device + '"'+
                ' cweb-tools-api="'+ baseCWebPDFApi +'"'+
                cmistagstr+
                ' class="'+className+'"' +
                '>'+
                '</cmis>';
            $('#testThis').empty().prepend(cmisTag);
            console.log(cmisTag);
            angular.module('test', ['UCX.Cmis']);
            if(!angular.element(document).injector()){
                angular.element(document).ready(function () { angular.bootstrap(document.getElementById('testThis'), ['test']); });
            }
        }
        function initView(url,token,path,lang,baseUrl){
            var className,language;
            if(!path){
                path='/';
            }
            baseUrl+='/';
            var device = 'phantom-online';
            if (navigator.userAgent.match(/mobile|Android|iPhone|ios|iPod/i)){
                device = 'mobile';
            }
            if(device === 'mobile'){
                className='platform platform-mobile';
            }else{
                className=''
            }
            var cmistagstr = '';
            if (urlInfoParams.pluginui){
                cmistagstr = cmistagstr + ' plugin-ui="'+ urlInfoParams.pluginui +'" ';
                className = 'plugin-ui-list';
            }
            if (urlInfoParams.lang){
                language = urlInfoParams.lang
            }else{
                language = lang;
            }
            if (urlInfoParams.filetype){
                cmistagstr = cmistagstr + ' file-type="'+ urlInfoParams.filetype +'" ';
            }
            if (urlInfoParams.fileselectmode){
                cmistagstr = cmistagstr + ' file-select-mode="'+ urlInfoParams.fileselectmode +'" ';
            }
            if (urlInfoParams.filepickermodal){
                cmistagstr = cmistagstr + ' file-picker-modal="'+ urlInfoParams.filepickermodal +'" ';
            }
            var phantomSubscriptionStatus=null;
            var paramsPath = urlInfoParams['path'];
            phantomSubscriptionStatus=false;
            generateCmisTag(url,className,token,path,language,baseUrl,device,cmistagstr,phantomSubscriptionStatus)
        }
        function getCookie(name)
        {
            var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
            if(arr=document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return '';
        }
        var token =encodeURIComponent(decodeURIComponent(decodeURIComponent(getCookie('currentToken'))));
        console.log('=====token',token)
        var lang = urlInfoParams.lang;
        var url = baseUrl+'/cmis/browser';
        var email = getCookie('currentEmail');
        var path = calculatePath(email);
        if (localStorage.getItem('currentLang')) {
            lang = localStorage.getItem('currentLang'); // e.g., zh-CN
        }

        //  判断 token 是否过期
//         isTokenExpires(token,function(data){
//             $('.loading').hide();
//             $('.token-error').addClass('hide');
//             initView(url,token,path,lang,baseUrl)
//
//         },function(data){
// //        console.log(data)
//             $('.loading').hide();
//             $('.token-error').removeClass('hide');
//         },baseUrl);
//         $(document).on('touchstart',function(){
//             // window.parent.angularHeaderComponent.zone.run(function(){
//             //     window.parent.angularHeaderComponent.closeDropdowns();
//             // });
//         });

        function switchListByEmail(email){
            isTokenExpires(token,function(data){
                $('.loading').hide();
                $('.token-error').addClass('hide');
                var path = calculatePath(email);
                $("#testThis").replaceWith($cleanCopy.clone());
                initView(url,token,path,lang,baseUrl)
            },function(data){
//        console.log(data)
                $('.loading').hide();
                $('.token-error').removeClass('hide');
            },baseUrl);
        }


        $('.test').click(function(){
            var email = $(this).html();
            console.log(email);
            switchListByEmail(email);
        });
        $('#changePath').click(function(){
            window.location.href=window.location.href+'?path=321'
        });
        function GetFileExtension(fileName){
            var nPos=fileName.lastIndexOf(".");
            if(nPos <= 0)
                return "";
            var nFileLen=fileName.length;
            var suffix=fileName.substring(nPos+1,nFileLen);
            return suffix;
        }
        function isSupportedFile(fileName){
            var extName = GetFileExtension(fileName);
            if(extName === "")
                return {ret:false};
            extName = extName.toLowerCase();
            // return true;
            if(extName === "jpg" || extName === "jpeg" ||
                extName === "bmp" || extName === "png" || extName === "gif" ||
                extName === "tiff" || extName === "jpx" || extName === "tif"){
                return {ret:true, convertType: window.top.WebTools.ConvertType.IMGTOPDF};
            } else if(extName === "txt") {
                return {ret:true, convertType: window.top.WebTools.ConvertType.Text2PDF};
            } else if(extName === "ppt" || extName === "pptx") {
                return {ret:true, convertType: window.top.WebTools.ConvertType.PPTTOPDF};
            } else if(extName === "doc" || extName === "docx"){
                return {ret:true, convertType: window.top.WebTools.ConvertType.WORDTOPDF};
            } else if(extName === "xls" || extName === "xlsx"){
                return {ret:true, convertType: window.top.WebTools.ConvertType.EXCELTOPDF};
            } else if(extName === "pdf" ){
                return {ret:true, convertType: window.top.WebTools.ConvertType.PREVIEWPDF};
            }
            return {ret:false};

        }

        window.viewDocument = function(objectId, downloadUrl, indexUrl, fileName, fileSize){
            return false;
            if (urlInfoParams.pluginui || urlInfoParams.filetype || urlInfoParams.fileselectmode){
                return false;
            }
            var url;
            if(indexUrl){
                url = encodeURIComponent(decodeURIComponent(indexUrl));
            }
            if(downloadUrl) {
                url = encodeURIComponent(decodeURIComponent(downloadUrl));
            }
            objectId = objectId.split(",")[0];
            //preview/url/:url/:cmisid
            var result = isSupportedFile(fileName);
            if (result.ret){
                var fileInfo = {};
                fileInfo.from = "FoxitDrive";
                fileInfo.file = objectId;
                fileInfo.fileName = fileName;
                fileInfo.size = fileSize;
                fileInfo.dataType = "CMISFileId";
                fileInfo.password = "";
                setTimeout(function() {
                    window.top.tools.doPreviewFileForFoxitDrive(fileInfo, result.convertType);
                }, 500);
                return ;
            }
            setTimeout(function() {
                window.top.doPreviewFileFromFoxitDrive(objectId);
            }, 500);
        };
        window.foxitDriveLoaded = function(data){
            window.top && window.top.foxitDriveLoadedEvent && window.top.foxitDriveLoadedEvent(data);
        };
        window.sendGa = function(type,options){
            var fromWhich;
            if(urlInfoParams['path']){
                if(urlInfoParams['path']!=='Reading'){
                    fromWhich = 'Shared With Me'
                }else{
                    fromWhich = 'Foxit Drive'
                }
            }else{
                fromWhich = 'Foxit Drive'
            }

            var label= fromWhich+ ' ' + options.eventAction+ ' ' +options.eventCategory+ ' '+options.eventLabel;
            var action = fromWhich+ ' ' + options.eventAction+ ' ' +options.eventCategory;
            if(window.top && window.top.jRsRgaSend && (options.eventAction || options.eventCategory)){
                window.top.jRsRgaSend(label, 'Foxit Drive', action);
            }
        };

        if(urlInfoParams && urlInfoParams['pluginui'] || urlInfoParams && urlInfoParams['path']){

        }else{
            // 仅针对 foxit drive 刷新 其他地方的不刷新
            window.top.addEventListener('message', function(event) {
                if (event && event.data && event.data.eventName) {
                    if (event.data.eventName === 'foxitDriveNeedRefreshList') {
                        window.CloudReading.refreshCurFolderList()
                    }
                }
            });
        }
    })();


</script>

</body>
</html>


